import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Button, Typography, Select, message, Input } from 'antd';
import { BaseTable, utils } from '@/components/BaseTable';
import PageEmpty from '@/components/PageEmpty';
import _ from 'lodash';
import {
  CONSTANT_TAB_KEY1, // 投资正式版
  CONSTANT_TAB_KEY2, // 调整版
  CONSTANT_TAB_KEY3, // 实际版
} from '../utils/constant';
import { getCityData } from '../utils/request';

const { Text } = Typography;

const Page = props => {
  const { yearMonth, setExportExcel } = props;
  // 展开项
  const [expandKeys, setExpandKeys] = useState([]);
  const [expandKeysCopy, setExpandKeysCopy] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectValue, setSelectValue] = useState(0);
  const [searchValue, setSearchValue] = useState('');
  const [tableMap, setTableMap] = useState({
    headerRenderer: [],
    columns: [],
    data: [],
  });
  // const changeLoading = boolean => {
  //   setLoading(boolean);
  //   setExportExcel(boolean);
  // };
  // 获取列表数据
  const getData = async (params, callback) => {
    setLoading(true);
    const res = await getCityData(params, searchValue);
    const { headerRenderer, columns, data } = res;
    setExportExcel(!data.length);
    setLoading(false);
    setTableMap({
      headerRenderer,
      columns,
      data,
    });
    setExpandKeys([]);
    setSelectValue(0);
    setExpandKeysCopy(data.map(tar => tar.id));
    if (callback) callback();
  };
  // 展开/关闭 所有二级
  const selectChange = (val, a, c) => {
    setSelectValue(val);
    if (val) {
      // val===1 打开全部
      setExpandKeys(expandKeysCopy);
      setTableMap({
        ...tableMap,
        data: tableMap.data.map(tar => {
          if (tar.rowSpan) {
            return { ...tar, rowSpan: tar.maxRowNum };
          }
          return { ...tar };
        }),
      });
      return;
    }
    // 关闭全部
    setExpandKeys([]);
    setTableMap({
      ...tableMap,
      data: tableMap.data.map(tar => {
        if (tar.rowSpan) {
          return { ...tar, rowSpan: tar.minRowNum };
        }
        return { ...tar };
      }),
    });
  };
  // 表格内展开关闭
  const onExpandedRowsChange = val => {
    setSelectValue(Number(val.length && val.length !== 0));
    setExpandKeys(val);
  };
  // 表格内展开关闭
  const onRowExpand = val => {
    console.log('onRowExpand', val);
    const {
      expanded,
      rowData: { pid, children },
    } = val;
    // 改变值  是点击row 的 children 的数量
    const difference = children.length;
    const rowSpanIndex = tableMap.data.findIndex(tar => tar.pid === pid && tar.rowSpan);
    const newData = tableMap.data;
    // 增加
    if (expanded) {
      newData[rowSpanIndex].rowSpan += difference;
      setTableMap({ ...tableMap, data: [...newData] });
      return;
    }
    newData[rowSpanIndex].rowSpan -= difference;
    setTableMap({ ...tableMap, data: [...newData] });
  };
  const rowRenderer = ({ rowData, rowIndex, cells, columns }) => {
    const cell = cells[0];
    if (rowData.rowSpan) {
      const style = {
        ...cell.props.style,
        backgroundColor: 'white',
        height: rowData.rowSpan * 36 - 1,
        alignSelf: 'flex-start',
        zIndex: 1,
      };
      cells[0] = React.cloneElement(cell, { style });
    }
    return cells;
  };

  useEffect(() => {
    // 初始化(或者月份改变)获取数据,并且恢复 select 恢复默认值
    getData({
      yearMonth,
    });
  }, [yearMonth, searchValue]);
  return (
    <>
      <Row
        gutter={[5, 0]}
        type="flex"
        justify="space-between"
        align="middle"
        style={{ marginBottom: 10 }}
      >
        <Col>
          <Text>层级：&ensp;</Text>
          <Select
            size="small"
            onChange={selectChange}
            dropdownMatchSelectWidth={false}
            className="version-select"
            value={selectValue}
          >
            <Select.Option key={1} value={1}>
              标准业态
            </Select.Option>
            <Select.Option key={2} value={0}>
              业态分类
            </Select.Option>
          </Select>
        </Col>
        <Col>
          <Input.Search
            size="small"
            placeholder="输入城市名称搜索"
            onSearch={value => setSearchValue(value)}
            loading={loading}
          />
        </Col>
      </Row>
      {loading ? (
        <PageEmpty emptyTitle="加载中..." />
      ) : (
        <BaseTable
          subtractHeight="160px"
          expandedRowKeys={expandKeys}
          onExpandedRowsChange={onExpandedRowsChange}
          onRowExpand={onRowExpand}
          expandColumnKey="productType"
          fixedColumns={tableMap.columns}
          headerHeight={[30]}
          headerRenderer={utils.getHeaderRenderer(tableMap.headerRenderer, 1)}
          treeData={tableMap.data}
          rowRenderer={rowRenderer}
          overscanRowCount={5}
        />
      )}
    </>
  );
};

export default Page;
